<?php


namespace Frieza\Modules\Search\Controllers;


use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\SearchIntervention;
use Doraemon\model\SearchInterventionKeyword;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\pockets\excel\ReadExcel;
use Doraemon\tools\BlockType;
use Doraemon\tools\Checker;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;


class SearchInterventionController extends Controller
{

    const rules = [
        'keyword' => 'required',
        'page' => 'required|size:2|string',
        'obj_id' => 'required',
        'position' => 'integer|max:40',
        'detele' => 'max:1'
    ];

    const message = [
        'required' => '参数 :attribute是必须传递参数.',
        'max' => '参数 :attribute 不能大于 :max.',
        'integer' => '参数 :attribute是必须是整型'
    ];

    public function index(Request $request, Content $content)
    {
        $where = $this->buildWhere($request);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $list = SearchIntervention::getList($where);
        return $content
            ->header('搜索干预')
            ->row($this->listAction($list, $pageSize));
    }

    public function listAction($list, $pageSize)
    {
        $gridModel = new pGridDataModel($list, SearchIntervention::count(), ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(8, function ($filter) {
                    $filter->equal('keyword', '关键字')->placeholder("请输入关键字");
                });
                $filter->expand();
            });
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append("<a href='/admin/search/searchIntervention/downExcel' class='btn button-success'><i class='fa fa-file-excel-o'></i>>导出模板</a>");
                $url = '/admin/search/searchIntervention/importExcel';
                $tools->append('<a href="javascript:layer.open({
                                type: 2,
                                title: \'导入\',
                                maxmin: true,
                                area: [\'400px\', \'500px\'],
                                content: \'' . $url . '\'
                            });" class="btn button-success"><i class="fa fa-upload"></i>导入</a><br/>'
                );
            });
            $grid->column('keyword', '关键字');
            $grid->column('record_default', '默认搜索干预记录数');
            $grid->column('record_newest', '最新搜索干预记录数');
            $grid->column('edittime', '最后一次干预时间')->display(function ($edittime) {
                if ($edittime) {
                    return date("Y-m-d H:i:s", $edittime);
                }
                return "尚未添加搜索干预";
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a href="/admin/search/searchIntervention/' . $actions->row->id . '/check" class="fa fa-info-circle">查看</a>');
            });
        });
        return $grid;
    }

    public function createKeyword(Content $content)
    {
        $tab = new Tab();
        $form = new Form();

        $form->text('keyword', '关键字')->required();
        $form->action('/admin/search/searchIntervention/saveKeyword');
        $tab->add('添加关键字', $form, true);
        $content->header('添加关键字')
            ->breadcrumb([
                'text' => '搜索干预',
                'url' => '/search/searchIntervention/index'
            ], ['text' => '添加关键字'])
            ->row($tab);
        return $content;

    }


    public function saveKeyword(Request $request)
    {
        try {
            $data = array();
            $keyword = $request->input('keyword');
            if (SearchIntervention::isHasKeyword($keyword)) {
                throw new \Exception('关键字存在');
            } else {
                $data['keyword'] = $keyword;
                $data['operator_id'] = Admin::user()->id;
                $data['addtime'] = time();
                $data['search_status'] = SearchIntervention::STATUS_NORMAL;
                $data['operator_name'] = Admin::user()->find($data['operator_id'])->name;
                SearchIntervention::insert($data);
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect('/admin/search/searchIntervention/index')->with(compact('success'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    //二级页->默认排序
    public function check(Request $request, Content $content, $id)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $tab = new Tab();
        $where = array(
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_DEFAULT,
            'related_id' => $id,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL,
            'ORDER' => ['intervention_position' => 'DESC'],
            'LIMIT' => [($page - 1) * $pageSize, $pageSize]
        );
        $list = SearchInterventionKeyword::getList($where);

        $countWhere = [
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_DEFAULT,
            'related_id' => $id,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL
        ];
        $count = SearchInterventionKeyword::count($countWhere);

        $gridModel = new pGridDataModel($list, $count, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->column('sort_type', '干预页面')->using(SearchInterventionKeyword::SORT_TYPE_MAP);
            $grid->column('content_type', '内容类型')->using(BlockType::TYPE_NAME_MAP);
            $grid->column('obj_id', '内容ID')->display(function ($obj_id) {
                $type = IdParse::getType($obj_id);
                switch ($type) {
                    case BlockType::TYPE_PHOTO:
                        return "<a href='https://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->obj_id' target='_blank'>" . $this->obj_id . "</a>";
                    case BlockType::TYPE_ARTICLE:
                        return "<a href='https://frieza.haohaozhu.me/admin/article/select/audit/$this->obj_id' target='_blank'>" . $this->obj_id . "</a>";
                    case BlockType::TYPE_BLANK:
                        return "<a href='https://frieza.haohaozhu.me/admin/blank/select/audit/$this->obj_id?category=' target='_blank'>" . $this->obj_id . "</a>";
                    default :
                        return $this->obj_id;
                }
            });
            $grid->column('intervention_position', '干预位置');
            $grid->column('operator_name', '操作人');
            $grid->column('edittime', '操作时间')->display(function ($edittime) {
                return date("Y-m-d H:i:s", $edittime);
            });
            $this->script = <<<EOT
        $('.grid-row-pass').unbind('click').click(function() {
            var id = $(this).data('id');

            swal({
                title: "确定删除？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/search/searchIntervention/' + id + '/delete',
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '删除失败', 'error');
                            }else{
                                swal(data.msg, '删除成功', 'success');
                            }
                        }
                    });
                }
            });
        });
EOT;
            Admin::script($this->script);
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->append("<div class='mb-5'><a class='btn btn-xs action-btn btn-primary grid-row-pass' data-id='{$actions->getKey()}'><i class='fa fa-check'></i>删除</a></div>");
            });
        });

        $tab->add('默认排序', $grid->render(), true);
        $tab->addLink('最新排序', '/admin/search/searchIntervention/' . $id . '/check/newest');
        $content->row($tab);
        return $content->header('干预记录详情(' . SearchIntervention::getKeywordNameById($id) . ')')
            ->breadcrumb(['text' => '搜索干预',
                'url' => '/search/searchIntervention/index'],
                ['text' => '干预记录详情']);
    }

    //二级页->最新排序
    public function checkNewest(Request $request, Content $content, $id)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $tab = new Tab();
        $where = array(
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_NEWEST,
            'related_id' => $id,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL,
            'ORDER' => ['intervention_position' => 'DESC'],
            'LIMIT' => [($page - 1) * $pageSize, $pageSize]
        );
        $list = SearchInterventionKeyword::getList($where);

        $countWhere = [
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_NEWEST,
            'related_id' => $id,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL
        ];
        $count = SearchInterventionKeyword::count($countWhere);

        $gridModel = new pGridDataModel($list, $count, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->column('sort_type', '干预页面')->using(SearchInterventionKeyword::SORT_TYPE_MAP);
            $grid->column('content_type', '内容类型')->using(SearchInterventionKeyword::CONTENT_TYPE_MAP);
            $grid->column('obj_id', '内容ID')->display(function ($obj_id) {
                $type = IdParse::getType($obj_id);
                switch ($type) {
                    case BlockType::TYPE_PHOTO:
                        return "<a href='https://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->obj_id' target='_blank'>" . $this->obj_id . "</a>";
                    case BlockType::TYPE_ARTICLE:
                        return "<a href='https://frieza.haohaozhu.me/admin/article/select/audit/$this->obj_id' target='_blank'>" . $this->obj_id . "</a>";
                    case BlockType::TYPE_BLANK:
                        return "<a href='https://frieza.haohaozhu.me/admin/blank/select/audit/$this->obj_id?category=' target='_blank'>" . $this->obj_id . "</a>";
                    default:
                        return $this->obj_id;
                }
            });
            $grid->column('intervention_position', '干预位置');
            $grid->column('operator_name', '操作人');
            $grid->column('edittime', '操作时间')->display(function ($edittime) {
                return date("Y-m-d H:i:s", $edittime);
            });
            $this->script = <<<EOT
        $('.grid-row-pass').unbind('click').click(function() {
            var id = $(this).data('id');

            swal({
                title: "确定删除？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/search/searchIntervention/' + id + '/delete',
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '删除失败', 'error');
                            }else{
                                swal(data.msg, '删除成功', 'success');
                            }
                        }
                    });
                }
            });
        });
EOT;
            Admin::script($this->script);
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->append("<div class='mb-5'><a class='btn btn-xs action-btn btn-primary grid-row-pass' data-id='{$actions->getKey()}'><i class='fa fa-check'></i>删除</a></div>");
            });
        });

        $tab->addLink('默认排序', '/admin/search/searchIntervention/' . $id . '/check');
        $tab->add('最新排序', $grid->render(), true);
        $content->row($tab);
        return $content->header('干预记录详情(' . SearchIntervention::getKeywordNameById($id) . ')')
            ->breadcrumb(['text' => '搜索干预',
                'url' => '/search/searchIntervention/index'],
                ['text' => '干预记录详情']);
    }


    public function createSearchIntervention(Request $request, Content $content, $id)
    {

        $tab = new Tab();
        $form = new Form();
        $form->radio('sort_type', '干预界面')
            ->options(
                [SearchInterventionKeyword::SORT_TYPE_DEFAULT => '综合-默认',
                    SearchInterventionKeyword::SORT_TYPE_NEWEST => '综合-最新']
            )
            ->default(function () {
                $url = $_SERVER['REQUEST_URI'];
                if (strpos($url, 'newest') != false) {
                    return SearchInterventionKeyword::SORT_TYPE_NEWEST;
                } else {
                    return SearchInterventionKeyword::SORT_TYPE_DEFAULT;
                }
            });
        $form->text('obj_id', '内容ID')->required();
        $form->text('intervention_position', '干预位置')->required();
        $form->action('/admin/search/searchIntervention/' . $id . '/saveSearchInv');
        $tab->add('添加搜索干预', $form, true);
        $content->header('添加搜索干预(' . SearchIntervention::getKeywordNameById($id) . ')')
            ->breadcrumb(
                ['text' => '搜索干预', 'url' => '/search/searchIntervention/index'],
                ['text' => '干预记录详情', 'url' => '/search/searchIntervention/' . $id . '/check'],
                ['text' => '添加搜索干预',]
            )
            ->row($tab);
        return $content;
    }

    //干预搜索
    public function saveSearchIntervention(Request $request, $id)
    {

        $data = array();
        $params = $request->all();
        if (!Checker::isObjid($params['obj_id'])) {
            $error = new MessageBag(['title' => 'id非法']);
            return back()->with(compact('error'));
        }
        $params['intervention_position'] = (int)$params['intervention_position'];
        if ($params['intervention_position'] > 40 || $params['intervention_position'] < 0) {
            $error = new MessageBag(['title' => '超出干预位置']);
            return back()->with(compact('error'));
        }
        if (!is_int($params['intervention_position'])) {
            $error = new MessageBag(['title' => '请输入正确的格式']);
            return back()->with(compact('error'));
        }
        //判断干预类型是否为隐藏
        if ($params['intervention_position'] == 0) {
            $data['intervention_position'] = 0;
            $data['operate_type'] = SearchInterventionKeyword::OPERATE_TYPE_HIDE;
        } else {
            $data['intervention_position'] = $params['intervention_position'];
            $data['operate_type'] = SearchInterventionKeyword::OPERATE_TYPE_NORMAL;
        }
        $data['related_id'] = $id;
        $data['sort_type'] = $params['sort_type'];
        $data['content_type'] = IdParse::getType($params['obj_id']);
        $data['obj_id'] = $params['obj_id'];
        $data['addtime'] = time();
        $data['edittime'] = time();
        $data['search_status'] = SearchInterventionKeyword::STATUS_NORMAL;
        $data['operator_id'] = Admin::user()->id;
        $data['operator_name'] = Admin::user()->name;
        SearchInterventionKeyword::insert($data);
        //更新主表记录数
        $record_default = SearchInterventionKeyword::count(['related_id' => $id,
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_DEFAULT,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL

        ]);
        $record_newest = SearchInterventionKeyword::count(['related_id' => $id,
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_NEWEST,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL
        ]);
        $t = ['record_default' => $record_default, 'record_newest' => $record_newest, 'edittime' => time()];
        SearchIntervention::update($t, ['id' => $id]);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/search/searchIntervention/' . $id . '/check')->with(compact('success'));
    }

    //修改干预表单
    public function updateSearchIntervention(Request $request, Content $content, $related_id, $id)
    {
        //纯显示 不可更改内容
        $data = array(
            'objId' => SearchInterventionKeyword::getObjid($id),
            'typeId' => SearchInterventionKeyword::get('content_type', ['id' => $id]),
            'inv_position' => SearchInterventionKeyword::get('intervention_position', ['id' => $id]),
            'query' => SearchIntervention::getKeywordNameById($related_id)
        );

        $tab = new Tab();
        $form = new Form($data);
        $form->display('objId', '内容id')->disable();
        $form->display('typeId', '内容类型')->disable();
        $form->display('inv_position', '修改前干预位置');
        $form->display('query', '关键词');
        $form->text('intervention_position', '修改后干预位置')->required();
        $form->action('/admin/search/searchIntervention/' . $related_id . '/check/' . $id . '/editUpload');

        $tab->add('修改搜索干预', $form, true);
        $content->header('修改搜索干预')
            ->breadcrumb(
                ['text' => '搜索干预', 'url' => '/search/searchIntervention/index'],
                ['text' => '干预记录详情', 'url' => '/search/searchIntervention/' . $related_id . '/check'],
                ['text' => '修改搜索干预',]
            )
            ->row($tab);
        return $content;
    }

    //修改提交
    public function editSearchIntervention(Request $request, $related_id, $id)
    {
        $intervention_position = $request->input('intervention_position');
        if ($intervention_position > 20 || $intervention_position < 0) {
            $error = new MessageBag(['title' => '超出干预位置']);
            return back()->with(compact('error'));
        }
        $data = ['intervention_position' => $intervention_position, 'edittime' => time()];
        SearchInterventionKeyword::update($data, ['id' => $id]);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/search/searchIntervention/' . $related_id . '/check')->with(compact('success'));
    }

    //软删除
    public function deleteSearchIntervention($id)
    {
        $delete = SearchInterventionKeyword::update(['search_status' => SearchInterventionKeyword::STATUS_DELETE], ['id' => $id]);
        //更新主表记录数
        $related_id = SearchInterventionKeyword::get('related_id', ['id' => $id]);
        $record_default = SearchInterventionKeyword::count(['related_id' => $related_id,
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_DEFAULT,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL
        ]);
        $record_newest = SearchInterventionKeyword::count(['related_id' => $related_id,
            'sort_type' => SearchInterventionKeyword::SORT_TYPE_NEWEST,
            'search_status' => SearchInterventionKeyword::STATUS_NORMAL
        ]);
        $t = ['record_default' => $record_default, 'record_newest' => $record_newest];
        $update = SearchIntervention::update($t, ['id' => $related_id]);
        if ($update && $delete) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return back()->with(compact('success'));
        }
    }

    public function buildWhere(Request $request)
    {
        $params = $request->all();
        $where = [];
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        if ($params['keyword']) {
            $where['search_status'] = SearchIntervention::STATUS_NORMAL;
            $where['keyword[~]'] = $params['keyword'];
            $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        } else {
            $where['search_status'] = SearchIntervention::STATUS_NORMAL;
            $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        }
        return $where;
    }

    public function downExcel()
    {
        $downExcel = new DownExcel();
        $title = '搜索干预模板';
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $data = [
            0 => ['例:客厅', '最新或默认', ' ', '干预位置不超过40', '1为删除']
        ];
        $head = [
            '关键字', '干预页面', '内容id', '干预位置', '删除操作'
        ];
        $downExcel->create($data, $head);
        return back();
    }

    public function importExcel(WorkContent $content)
    {
        $form = new Form();
        $form->file('excel', '上传Excel')->required()->removable()->help('请严格按照模板格式');
        $form->action('/admin/search/searchIntervention/saveExcel');
        return $content->body($form);
    }

    public function saveExcel(Request $request)
    {
        $params = $request->all();
        $newFile = 'searchIntervention-' . date('YmdHis') . '.xls';
        $newFilePath = '/tmp' . '/' . $newFile;
        $rs = move_uploaded_file($params['excel'], $newFilePath);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '文件保存失败'
            ]);
            return back()->with(compact('error'));
        }
        $excel = new ReadExcel($newFile);
        $excelData = $excel->getExcelDataNoHeader($newFilePath);
        //key：关键字 干预页面 内容id 干预位置 删除操作
        $excelKeyArray = ['keyword', 'page', 'obj_id', 'position', 'delete'];
        $iMax = count($excelData);
        //检查 格式化
        for ($i = 1; $i < $iMax; $i++) {
            $singleData = array_combine($excelKeyArray, $excelData[$i]);
            if (is_null($singleData['keyword'])) {
                break;
            }
            //筛查 有一条不符合直接返回
            $validator = Validator::make($singleData, self::rules, self::message);
            if ($validator->fails()) {
                return $validator->errors()->first();
            }
            //页面不是最新或者默认 则直接返回
            if (!($singleData['page'] === '默认') && !($singleData['page'] === '最新')) {
                $error = new MessageBag([
                    'title' => '干预页面有不支持变量'
                ]);
                return back()->with(compact('error'));
            }
            //校验id 不是objId直接返回
            $isObjId = Checker::isObjid($singleData['obj_id']);
            if (!$isObjId) {
                $error = new MessageBag([
                    'title' => 'objid:' . $singleData['obj_id'] . '格式错误'
                ]);
                return back()->with(compact('error'));
            }
            $data[] = $singleData;
        }
        //更新数据
        $iMax = count($data);
        for ($i = 0; $i < $iMax; $i++) {
            //主表是否有新加的关键字
            $hadKeyWord = SearchIntervention::isHasKeyword($data[$i]['keyword']);
            if ($hadKeyWord) {
                $master = [
                    'edittime' => time(),
                    'search_status' => SearchIntervention::STATUS_NORMAL,
                    'operator_id' => Admin::user()->id,
                    'operator_name' => Admin::user()->name,
                ];
                $result = SearchIntervention::update($master, ['keyword' => $data[$i]['keyword']]);
                Log::debug('更新关键字', [
                    'keyword' => $data[$i]['keyword'],
                    'name' => Admin::user()->name
                ]);
            } else {
                $master = [
                    'keyword' => $data[$i]['keyword'],
                    'addtime' => time(),
                    'edittime' => time(),
                    'search_status' => SearchIntervention::STATUS_NORMAL,
                    'operator_id' => Admin::user()->id,
                    'operator_name' => Admin::user()->name,
                ];
                $result = SearchIntervention::insert($master);
                Log::debug('新增关键字', [
                    'keyword' => $data[$i]['keyword'],
                    'name' => Admin::user()->name
                ]);
            }
            //更新从表
            if ($result) {
                $relatedId = SearchIntervention::get('id', ['keyword' => $data[$i]['keyword']]);
                //查看从表是否有过此obj_id的干预记录
                $where = [
                    'obj_id' => $data[$i]['obj_id'],
                    'related_id' => $relatedId,
                    'sort_type' => $data[$i]['page'] === '最新' ? SearchInterventionKeyword::SORT_TYPE_NEWEST : SearchInterventionKeyword::SORT_TYPE_DEFAULT,
                ];
                $hadObjId = SearchInterventionKeyword::get('*', $where);
                if ($hadObjId) {
                    //更新
                    $follow = [
                        'related_id' => $relatedId,
                        'sort_type' => $data[$i]['page'] === '最新' ? SearchInterventionKeyword::SORT_TYPE_NEWEST : SearchInterventionKeyword::SORT_TYPE_DEFAULT,
                        'content_type' => IdParse::getType($data[$i]['obj_id']),
                        'operate_type' => $data[$i]['position'] == 0 ? SearchInterventionKeyword::OPERATE_TYPE_HIDE : SearchInterventionKeyword::OPERATE_TYPE_NORMAL,
                        'intervention_position' => $data[$i]['position'],
                        'addtime' => time(),
                        'edittime' => time(),
                        'search_status' => $data[$i]['delete'] == 1 ? SearchInterventionKeyword::STATUS_DELETE : SearchInterventionKeyword::STATUS_NORMAL,
                        'operator_id' => Admin::user()->id,
                        'operator_name' => Admin::user()->name
                    ];
                    $result = SearchInterventionKeyword::update($follow, $where);
                    Log::debug('更新干预位置', [
                        'keyword' => $data[$i]['keyword'],
                        'obj_id' => $data[$i]['obj_id'],
                        'sort_type' => $data[$i]['page'],
                        'position' => $follow['intervention_position'],
                        'name' => Admin::user()->name
                    ]);
                } else {
                    //插入
                    $follow = [
                        'related_id' => $relatedId,
                        'obj_id' => $data[$i]['obj_id'],
                        'sort_type' => $data[$i]['page'] === '最新' ? SearchInterventionKeyword::SORT_TYPE_NEWEST : SearchInterventionKeyword::SORT_TYPE_DEFAULT,
                        'content_type' => IdParse::getType($data[$i]['obj_id']),
                        'operate_type' => $data[$i]['position'] == 0 ? SearchInterventionKeyword::OPERATE_TYPE_HIDE : SearchInterventionKeyword::OPERATE_TYPE_NORMAL,
                        'intervention_position' => $data[$i]['position'],
                        'addtime' => time(),
                        'edittime' => time(),
                        'search_status' => $data[$i]['delete'] == 1 ? SearchInterventionKeyword::STATUS_DELETE : SearchInterventionKeyword::STATUS_NORMAL,
                        'operator_id' => Admin::user()->id,
                        'operator_name' => Admin::user()->name
                    ];
                    $result = SearchInterventionKeyword::insert($follow);
                    Log::debug('新增干预位置', [
                        'keyword' => $data[$i]['keyword'],
                        'obj_id' => $data[$i]['obj_id'],
                        'sort_type' => $data[$i]['page'],
                        'position' => $follow['intervention_position'],
                        'name' => Admin::user()->name
                    ]);
                }
                $defaultCount = SearchInterventionKeyword::count(['related_id' => $relatedId, 'search_status' => SearchInterventionKeyword::STATUS_NORMAL, 'sort_type' => SearchInterventionKeyword::SORT_TYPE_DEFAULT]);
                $newCount = SearchInterventionKeyword::count(['related_id' => $relatedId, 'search_status' => SearchInterventionKeyword::STATUS_NORMAL, 'sort_type' => SearchInterventionKeyword::SORT_TYPE_NEWEST]);
                $countData = ['record_default' => $defaultCount, 'record_newest' => $newCount];
                SearchIntervention::update($countData, ['id' => $relatedId]);
                if (!$result) {
                    $error = new MessageBag([
                        'title' => '在操作第' . $i . '条失败'
                    ]);
                    Log::debug('批量更新干预位置第' . $i . '条失败', [
                        'keyword' => $data[$i]['keyword'],
                        'obj_id' => $data[$i]['obj_id'],
                        'sort_type' => $data[$i]['page'],
                        'position' => $follow['intervention_position'],
                        'name' => Admin::user()->name
                    ]);
                    return back()->with(compact('error'));
                }
            } else {
                $error = new MessageBag([
                    'title' => '在操作第' . $i . '条失败'
                ]);
                Log::debug('批量更新干预位置第' . $i . '条失败', [
                    'keyword' => $data[$i]['keyword'],
                    'obj_id' => $data[$i]['obj_id'],
                    'sort_type' => $data[$i]['page'],
                    'position' => $follow['intervention_position'],
                    'name' => Admin::user()->name
                ]);
                return back()->with(compact('error'));
            }
        }
        $success = new MessageBag([
            'title' => '批量导入完成',
        ]);
        Log::debug('本次excel操作人', [
            'name' => Admin::user()->name
        ]);
        return back()->with(compact('success'));
    }
}